import store from './store/index.js';

import {
    addAction,
    subAction,
    incAction,
    decAction
} from './store/actionCreators.js'

// store.subscribe(() => {
//     console.log(store.getState());
// })

// 基本做法
// console.log('dispatch前--dispatching action:', addAction(3));
// store.dispatch(addAction(3))
// console.log('dispatch后--new state', store.getState());

// console.log();
// store.dispatch(addAction(2))
// store.dispatch(subAction(5))
// store.dispatch(subAction(7))
// store.dispatch(incAction())
// store.dispatch(decAction())

// 实现输入日志
// 封装一个函数

// function dispatchAndLogging(action) {
//     console.log('dispatch前--dispatching action:', action);
//     store.dispatch(action)
//     console.log('dispatch后--new state', store.getState());
// }

// dispatchAndLogging(addAction(3))
// dispatchAndLogging(addAction(5))

// 函数的基础之上做一个优化:修改原有的dispatch
// hack技术:monkeyingpatch
// const next = store.dispatch
// function dispatchAndLogging(action) {
//     console.log('dispatch前--dispatching action:', action);
//     next(action);
//     console.log('dispatch后--new state', store.getState());
// }
// store.dispatch = dispatchAndLogging;

// store.dispatch(addAction(3))
// store.dispatch(addAction(5))

//封装
function patchLogging(store) {
    const next = store.dispatch
    function dispatchAndLogging(action) {
        console.log('dispatch前--dispatching action:', action);
        next(action);
        console.log('dispatch后--new state', store.getState());
    }
    // store.dispatch = dispatchAndLogging;

    return dispatchAndLogging;
}

//封装类似patchThunk的功能
function patchThunk(store) {
    const next = store.dispatch;

    function dispatchAndThunk(action) {
        if(typeof action === 'function') {
            action(store.dispatch, store.getState)
        } else {
            next(action);
        }
    }

    // store.dispatch = dispatchAndThunk;
    return dispatchAndThunk;   
}
patchLogging(store);
patchThunk(store);

// store.dispatch(addAction(3))
// store.dispatch(addAction(5))
//function foo(dispatch, getState) {
    // console.log(dispatch, getState);

    // 这里传入的是一个函数
    //dispatch(subAction(3));
//}

// store.dispatch(foo)
// [Function: dispatchAndThunk] [Function: getState]


//封装applyMiddleware
function applyMiddleware(...middlewares) {
    //浅拷贝 原本是要这样写的 我们不会修改原来的数据 
    // 所以注释掉
    // const newMiddleware = [...middlewares];

    middlewares.forEach(middleware => {
        //调用middleware相当于调用传来的patchLogging和patchThunk
        store.dispatch = middleware(store);
    })
}

applyMiddleware(patchLogging, patchThunk);